<template>
  <div class="MyCreate">
    <van-nav-bar
        title="我的创作"
        right-text="草稿箱"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
        @click-right="onClickRight"
    />
    <van-tabs v-model:active="activeTab" @change="onTabChange">
      <van-tab title="文章">
        <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
        >
          <van-cell
              v-for="article in articles"
              :key="article.articleId"
              :title="article.title"
              :label="article.content"
              :is-link="true"
              :to="'/articleDetails/' +article.articleId"
          >
            <van-row
                type="flex" justify="center" align="left" class="header">
            </van-row>
            <template #label>
              <div>{{article.views}}阅读</div>
              <div>{{article.commentsCount}}评论</div>
            </template>
          </van-cell>
        </van-list>
      </van-tab>
      <van-tab title="回答" name="a">
        <div class="scroll-container">
          <van-list v-model:loading="loading" finished-text="没有更多了" @load="onLoad">
            <template #default>
              <div class="card-container">
                <router-link v-for="(item, index) in list2" :key="index" :to="'/helpDetails/' + item.id" tag="div"
                             class="card" @click="setActiveIndex(index)">
                  <div class="card-header">
                <span class="author">
                  <img v-if="item.authorImageUrl" :src="item.authorImageUrl" alt="Author Avatar" class="card__avatar"/>
                  {{ item.authorUsername }} | {{ item.time }}
                </span>


                  </div>
                  <div class="card-content">
                    <img :src="item.image" alt="" class="image"/>
                    <h5>{{ item.title }}</h5>
                    <p v-if="!detailVisible || activeIndex !== index">{{ item.content.slice(0, 20) + '...' }}</p>
                    <p v-if="detailVisible && activeIndex === index">{{ item.content }}</p>
                  </div>
                  <div class="card-footer">
                    <div>
                      <van-icon name="like-o" size="16"/>
                      <span class="post-count">{{ item.follow }}</span>
                    </div>
                    <div @click="handleGoods(item.id)">
                      <van-icon name="comment-circle-o" size="30"/>
                    </div>
                  </div>

                </router-link>
              </div>
            </template>
          </van-list>
        </div>

        <van-floating-bubble v-if="activeName === 'a'" icon="chat" @click="onClickTan"/>

      </van-tab>
      <van-tab title="加油站">
        <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
        >
          <div class="feed-list">
            <div v-for="(item, index) in feedItems" :key="index" class="feed-item">
              <div class="feed-header">
                <img :src="item.imageUrl" alt="Avatar" class="avatar" />
                <div class="user-info">
                  <p class="username">{{ item.username }}</p>
                  <p class="timestamp">{{ item.timestamp }}</p>
                </div>
              </div>
              <p class="content">{{ item.content }}</p>
              <div class="actions">
                <button class="action-like">
                  <i class="like-icon"></i>{{ item.likesCount }}
                </button>
                <button class="action-comment">
                  <i class="comment-icon"></i>{{ item.commentsCount }}
                </button>
              </div>
            </div>
          </div>
        </van-list>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script setup>
import {ref} from 'vue'
import {useRouter} from "vue-router";
import axios from "axios";
import {showToast} from "vant";
import {get} from "../../util/request.js";
const router=useRouter();
const onClickLeft = () => {
  router.push("/my");
  // 返回按钮逻辑
};
//const avatarUrl=ref('https://cdn.pixabay.com/photo/2016/03/04/19/36/background-1236581_1280.jpg')
const activeTab = ref(0);
const loading = ref(false);
const list2 = ref([]);
const finished = ref(false);
const setActiveIndex = (index) => {
  activeIndex.value = index;
  detailVisible.value = true; // 当点击时，假设你想显示完整内容
};
const onTabChange = (tab) => {
  // 处理标签页切换逻辑
  if (tab === 'b') {
    fetchData(); // 当切换到"加油站"标签时发起请求
  } else if (tab === 'a') {
    chatQ()
    // 处理标签页的逻辑
  }
};
const chatQ = async () => {
  try {
    loading.value = true;
    const response = await axios.get('http://localhost:9099/circle/problem/selectProblemList');
    if (response.status === 200) {
      list2.value = response.data.data; // 假设返回的数据直接赋值给list1
      console.log(list2.value);
      //查询到数据后调用fetchUserDataForArticles方法，将用户名和头像信息添加到list2中，用articleId作为参数
      await fetchUserDataForArticles(list2.value);

      console.log(list2.value);
    } else {
      console.error('Request failed with status:', response.status);
    }
  } catch (error) {
    console.error('There was an error!', error);
  } finally {
    loading.value = false;
  }
};
const fetchUserDataForArticles = async (articles) => {
  //发起axios

  for (let article of articles) {
    try {
      const userDataResponse = await axios.get(`http://localhost:9090/user/user/selectUser?userId=${article.userId}`);
      if (userDataResponse.data.code === 0) {
        const userData = userDataResponse.data.data;
        article.authorUsername = userData.username;
        article.authorImageUrl = userData.imageUrl;
      } else {
        console.error()
      }
    } catch (error) {
      console.error(`Error fetching user data for userId: ${article.userId}`, error);
    }

  }
  return articles;
};
const fetchData = async () => {
  try {
    loading.value = true;
    const response = await axios.get('http://localhost:9099/circle/selectAll');
    if (response.status === 200) {
      list1.value = response.data.data; // 假设返回的数据直接赋值给list1

      await fetchUserDataForArticles(list1.value);
    } else {
      console.error('Request failed with status:', response.status);
    }
  } catch (error) {
    console.error('There was an error!', error);
  } finally {
    loading.value = false;
  }
};
const activeIndex = ref();
const detailVisible = ref(true);
const feedItems = ref([
  {
    imageUrl: "",
    username: "吴彦祖",
    timestamp: "22小时前",
    content: "这大概是个模型吧。（￣︶￣）",
    likesCount: 207,
    commentsCount: 501
  },
])
get(
'post/findAll'
).then(
    (data) => {
      console.log(JSON.stringify(data))
      // 加载状态结束
      loading.value = false;
      finished.value = true

      if (data.code == 0) {
        showToast("查询成功");
        feedItems.value = data.data;// 初始化界面
      } else {
        showToast("查询失败");
      }


    })
    .catch(
        function () {
          alert("服务器错误")
        }
    )
const onLoad = () => {
  axios({
    method: 'get', // post  get
    url: 'http://localhost:9091/study/article/all'
  }).then(
      (data) => {
        console.log(JSON.stringify(data))
        console.log("获取处理器的数据：" + JSON.stringify(data.data))
        var r = data.data;

        // 加载状态结束
        loading.value = false;
        finished.value = true

        if (r.code == 0) {
          showToast("查询成功");
          articles.value = r.data;// 初始化界面
        } else {
          showToast("查询失败");
        }


      })
      .catch(
          function () {
            alert("服务器错误")
          }
      )
};
const articles = ref([])
const onClickRight =()=>{
  router.push("/drafts");
}
</script>

<style scoped>
.MyCreate {
  padding: 16px;
}
.header {
  background-image: url("https://cdn.pixabay.com/photo/2016/03/04/19/36/background-1236581_1280.jpg");
  background-size: cover;
  height: 100px; /* 自定义高度 */
}
.scroll-container {
  max-height: 600px; /* 设置容器的最大高度 */
  overflow-y: auto; /* 添加垂直滚动条 */
}

.scroll-container {
  max-height: 600px; /* 设置容器的最大高度 */
  overflow-y: auto; /* 添加垂直滚动条 */
}

.banner-content h1 {
  font-size: 18px;
  margin-bottom: 10px;
}

.banner-content p {
  font-size: 14px;
  line-height: 1.5;
}


.item-content p {
  margin-bottom: 5px;
  color: #333;
  text-align: left; /* 添加这一行来使内容靠左对齐 */
}



.post-count {
  margin-left: 4px;
  color: #666;
}

.card__avatar {
  width: 50px; /* 根据需要设置合适的宽度和高度 */
  height: 50px;
  border-radius: 50%; /* 将边框半径设置为50%，即变为圆形 */
  object-fit: cover; /* 确保图片铺满整个圆形区域 */
}

.card-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  padding: 16px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
}

.card-content {
  padding-top: 16px;
}

.image {
  width: 100%;
  height: auto;
}

.card-footer {
  display: flex;
  justify-content: space-between; /* 分布空间，使项目位于容器的两端 */
  align-items: center; /* 垂直居中对齐 */
  padding: 8px 16px; /* 可选：增加内边距以改善视觉效果 */
}

</style>